import React, { useState, useEffect } from 'react';
import {
    Container,
    Box,
    Typography,
    Button,
    Paper,
    Breadcrumbs,
    Link as MuiLink,
    CircularProgress,
    Alert,
    Grid
} from '@mui/material';
import {
    ArrowBack as ArrowBackIcon,
    Home as HomeIcon,
    ViewInAr as ModelIcon,
    Edit as EditIcon,
    Delete as DeleteIcon,
    Upload as UploadIcon
} from '@mui/icons-material';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { motion } from 'framer-motion';

import { useModelContext } from '../contexts/ModelContext';
import ModelViewer from '../components/ModelViewer';

const ModelView = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const {
        models,
        loading,
        fetchModels,
        deleteModel
    } = useModelContext();

    const [model, setModel] = useState(null);
    const [notFound, setNotFound] = useState(false);
    const [error, setError] = useState(null);
    const [deleteConfirm, setDeleteConfirm] = useState(false);

    // 加载模型数据
    useEffect(() => {
        // 每次打开查看页面时强制刷新模型数据
        fetchModels();

        if (models && models.length > 0) {
            // 查找要查看的模型
            const foundModel = models.find(m => m.id === id);
            if (foundModel) {
                setModel(foundModel);
            } else {
                setNotFound(true);
            }
        }
    }, [id, models, fetchModels]);

    // 当models数组更新时重新查找当前模型
    useEffect(() => {
        if (models && models.length > 0) {
            const foundModel = models.find(m => m.id === id);
            if (foundModel) {
                setModel(foundModel);
                setNotFound(false);
            } else {
                setNotFound(true);
            }
        }
    }, [models, id]);

    // 处理返回列表
    const handleGoBack = () => {
        navigate('/models');
    };

    // 处理编辑
    const handleEdit = () => {
        // 根据模型类型导航到对应的编辑页面
        if (model.geometry) {
            navigate(`/models/geometry/edit/${id}`);
        } else {
            navigate(`/models/edit/${id}`);
        }
    };

    // 确认删除
    const handleDeleteConfirm = () => {
        setDeleteConfirm(true);
    };

    // 取消删除
    const handleDeleteCancel = () => {
        setDeleteConfirm(false);
    };

    // 执行删除
    const handleDelete = async () => {
        try {
            setError(null);
            await deleteModel(id);
            navigate('/models');
        } catch (err) {
            console.error('删除模型失败:', err);
            setError(err.message || '删除模型失败，请稍后再试');
            setDeleteConfirm(false);
        }
    };

    // 显示"未找到"错误
    if (notFound) {
        return (
            <Container maxWidth="md" sx={{ py: 8, textAlign: 'center' }}>
                <Alert severity="error" sx={{ mb: 4 }}>
                    找不到ID为 {id} 的模型
                </Alert>
                <Button
                    variant="contained"
                    startIcon={<ArrowBackIcon />}
                    onClick={handleGoBack}
                >
                    返回模型列表
                </Button>
            </Container>
        );
    }

    return (
        <Container maxWidth="xl" sx={{ py: 4 }}>
            <Box sx={{ mb: 4 }}>
                <Breadcrumbs aria-label="breadcrumb" sx={{ mb: 2 }}>
                    <MuiLink
                        component={Link}
                        to="/"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <HomeIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        首页
                    </MuiLink>
                    <MuiLink
                        component={Link}
                        to="/models"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <ModelIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        模型列表
                    </MuiLink>
                    <Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
                        <ModelIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        模型详情
                    </Typography>
                </Breadcrumbs>

                <Paper
                    component={motion.div}
                    initial={{ opacity: 0, y: -20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5 }}
                    elevation={0}
                    sx={{
                        p: 3,
                        backgroundImage: 'linear-gradient(120deg, #e0f7fa 0%, #bbdefb 100%)',
                        borderRadius: 4,
                        mb: 4,
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center'
                    }}
                >
                    <Box>
                        <Typography variant="h4" component="h1" sx={{ fontWeight: 700 }}>
                            模型详情
                        </Typography>
                        <Typography variant="body1" color="text.secondary">
                            {model ? `查看 "${model.name}"` : '加载模型信息...'}
                        </Typography>
                    </Box>
                    <Box sx={{ display: 'flex', gap: 2 }}>
                        <Button
                            variant="contained"
                            startIcon={<ArrowBackIcon />}
                            onClick={handleGoBack}
                            component={motion.button}
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                        >
                            返回列表
                        </Button>
                    </Box>
                </Paper>
            </Box>

            {error && (
                <Alert severity="error" sx={{ mb: 3 }}>
                    {error}
                </Alert>
            )}

            {loading && !model ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', p: 8 }}>
                    <CircularProgress />
                </Box>
            ) : model ? (
                <>
                    {/* 3D模型预览 */}
                    <ModelViewer model={model} height={500} showInfo={false} />

                    {/* 模型信息 */}
                    <Grid container spacing={3}>
                        <Grid item xs={12} md={6}>
                            <Paper sx={{ p: 3, borderRadius: 2, height: '100%' }}>
                                <Typography variant="h6" gutterBottom>
                                    模型信息
                                </Typography>
                                <Box sx={{ mt: 2 }}>
                                    <Typography variant="subtitle2" sx={{ fontWeight: 'bold' }}>
                                        名称
                                    </Typography>
                                    <Typography variant="body1" sx={{ mb: 2 }}>
                                        {model.name}
                                    </Typography>

                                    <Typography variant="subtitle2" sx={{ fontWeight: 'bold' }}>
                                        描述
                                    </Typography>
                                    <Typography variant="body1" sx={{ mb: 2 }}>
                                        {model.description || '无描述'}
                                    </Typography>

                                    <Typography variant="subtitle2" sx={{ fontWeight: 'bold' }}>
                                        创建时间
                                    </Typography>
                                    <Typography variant="body1" sx={{ mb: 2 }}>
                                        {model.createdAt ? new Date(model.createdAt).toLocaleString() : '未知'}
                                    </Typography>

                                    {model.geometry && (
                                        <>
                                            <Typography variant="subtitle2" sx={{ fontWeight: 'bold' }}>
                                                几何体类型
                                            </Typography>
                                            <Typography variant="body1" sx={{ mb: 2 }}>
                                                {model.geometry.type === 'cube' ? '立方体' :
                                                    model.geometry.type === 'sphere' ? '球体' : model.geometry.type}
                                            </Typography>
                                        </>
                                    )}
                                </Box>
                            </Paper>
                        </Grid>

                        <Grid item xs={12} md={6}>
                            <Paper sx={{ p: 3, borderRadius: 2, height: '100%' }}>
                                <Typography variant="h6" gutterBottom>
                                    操作
                                </Typography>
                                <Box sx={{ mt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
                                    <Button
                                        variant="contained"
                                        color="primary"
                                        startIcon={<EditIcon />}
                                        onClick={handleEdit}
                                        fullWidth
                                    >
                                        编辑模型
                                    </Button>

                                    <Button
                                        variant="contained"
                                        color="primary"
                                        startIcon={<UploadIcon />}
                                        component={Link}
                                        to={`/models/${id}/files`}
                                        fullWidth
                                    >
                                        文件管理
                                    </Button>

                                    {!deleteConfirm ? (
                                        <Button
                                            variant="outlined"
                                            color="error"
                                            startIcon={<DeleteIcon />}
                                            onClick={handleDeleteConfirm}
                                            fullWidth
                                        >
                                            删除模型
                                        </Button>
                                    ) : (
                                        <Box sx={{ display: 'flex', gap: 2 }}>
                                            <Button
                                                variant="outlined"
                                                onClick={handleDeleteCancel}
                                                sx={{ flex: 1 }}
                                            >
                                                取消
                                            </Button>
                                            <Button
                                                variant="contained"
                                                color="error"
                                                onClick={handleDelete}
                                                sx={{ flex: 1 }}
                                            >
                                                确认删除
                                            </Button>
                                        </Box>
                                    )}
                                </Box>
                            </Paper>
                        </Grid>
                    </Grid>
                </>
            ) : null}
        </Container>
    );
};

export default ModelView; 